import TheUpload from '@/components/Upload';
import { Button, DatePicker, Space, Table } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';

const App = ({ value, onChange }) => {
  const [tableDataSource, setTableDataSource] = useState([]);
  useEffect(() => {
    if (value?.length > 0) {
      setTableDataSource(value);
    }
  }, [value]);

  const columns = [
    {
      title: '质检日期',
      dataIndex: 'qualityDate',
      key: 'qualityDate',
      width: 170,
      render: (text, record) => (
        <DatePicker
          value={record?.qualityDate ? dayjs(record?.qualityDate) : null}
          format={'YYYY-MM-DD'}
          onChange={(date, dateString) => {
            const newArr = tableDataSource.concat([]);
            const ind = tableDataSource.findIndex((item) => item?.tableId === record?.tableId);
            newArr[ind] = { ...newArr[ind], qualityDate: dateString };
            setTableDataSource(newArr);
            onChange(newArr);
          }}
        />
      ),
    },
    {
      title: '质检类型',
      dataIndex: 'qualityType',
      width: 100,
      key: 'qualityType',
    },
    {
      title: '质检图片',
      dataIndex: 'qualityImageList',
      key: 'qualityImageList',
      render: (txt, record) => {
        return (
          <TheUpload
            listType="picture-card"
            maxCount={10}
            limitSize={5}
            // multiple={true}
            accept=".png, .jpg, .jpeg"
            value={txt || []}
            onChange={(list) => {
              const newArr = tableDataSource.concat([]);
              const ind = tableDataSource.findIndex((item) => item?.tableId === record?.tableId);
              const obj = { ...newArr[ind], qualityImageList: list };
              newArr.splice(ind, 1, obj);
              setTableDataSource(newArr);
              onChange(newArr);
            }}
          />
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 60,
      render: (_, record) => (
        <a
          onClick={() => {
            const newArr = tableDataSource.concat([]);
            const ind = tableDataSource.findIndex((item) => item?.tableId === record?.tableId);
            newArr.splice(ind, 1);
            setTableDataSource(newArr);
            onChange(newArr);
          }}
        >
          删除
        </a>
      ),
    },
  ];

  return (
    <Space direction="vertical" style={{ width: '100%' }}>
      <Button
        onClick={() => {
          const newArr = tableDataSource.concat([]);
          const now = new Date();
          newArr.push({ tableId: now.getTime() });
          setTableDataSource(newArr);
          onChange(newArr);
        }}
      >
        添加报告
      </Button>
      {tableDataSource.length > 0 && (
        <Table rowKey="tableId" columns={columns} pagination={null} dataSource={tableDataSource} />
      )}
    </Space>
  );
};
export default App;
